// 音效系统模块

class AudioManager {
  constructor() {
    this.audioContext = null;
    this.sounds = new Map();
    this.enabled = true;
    this.volume = 1.0;
    this.initialized = false;

    // 初始化音频上下文
    this.initAudioContext();
  }

  // 初始化方法（供外部调用）
  async init() {
    return new Promise((resolve) => {
      this.initAudioContext();
      resolve();
    });
  }

  // 初始化音频上下文
  initAudioContext() {
    try {
      // 创建音频上下文
      const AudioContext = window.AudioContext || window.webkitAudioContext;
      if (AudioContext) {
        this.audioContext = new AudioContext();
        this.masterGain = this.audioContext.createGain();
        this.masterGain.connect(this.audioContext.destination);
        this.masterGain.gain.value = this.volume;

        // 生成音效
        this.generateSounds();
        this.initialized = true;
      }
    } catch (error) {
      console.warn("音频初始化失败:", error);
      this.enabled = false;
    }
  }

  // 生成游戏音效
  generateSounds() {
    if (!this.audioContext) return;

    // 球体碰撞音效
    this.sounds.set("collision", this.createCollisionSound());

    // 合成成功音效（不同等级）
    for (let i = 1; i <= 9; i++) {
      this.sounds.set(`merge_${i}`, this.createMergeSound(i));
    }

    // 球体掉落音效
    this.sounds.set("drop", this.createDropSound());

    // 游戏结束音效
    this.sounds.set("gameOver", this.createGameOverSound());

    // 按钮点击音效
    this.sounds.set("click", this.createClickSound());

    // 道具使用音效
    this.sounds.set("powerup", this.createPowerUpSound());

    // 成就解锁音效
    this.sounds.set("achievement", this.createAchievementSound());
  }

  // 创建碰撞音效
  createCollisionSound() {
    return (volume = 0.3) => {
      if (!this.enabled || !this.audioContext) return;

      const oscillator = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator.connect(gainNode);
      gainNode.connect(this.masterGain);

      oscillator.type = "square";
      oscillator.frequency.setValueAtTime(200, this.audioContext.currentTime);
      oscillator.frequency.exponentialRampToValueAtTime(
        50,
        this.audioContext.currentTime + 0.1
      );

      gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(
        0.01,
        this.audioContext.currentTime + 0.1
      );

      oscillator.start(this.audioContext.currentTime);
      oscillator.stop(this.audioContext.currentTime + 0.1);
    };
  }

  // 创建合成音效
  createMergeSound(level) {
    return (volume = 0.5) => {
      if (!this.enabled || !this.audioContext) return;

      const baseFreq = 200 + level * 50; // 等级越高频率越高
      const oscillator1 = this.audioContext.createOscillator();
      const oscillator2 = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator1.connect(gainNode);
      oscillator2.connect(gainNode);
      gainNode.connect(this.masterGain);

      oscillator1.type = "sine";
      oscillator2.type = "triangle";

      oscillator1.frequency.setValueAtTime(
        baseFreq,
        this.audioContext.currentTime
      );
      oscillator2.frequency.setValueAtTime(
        baseFreq * 1.5,
        this.audioContext.currentTime
      );

      oscillator1.frequency.exponentialRampToValueAtTime(
        baseFreq * 2,
        this.audioContext.currentTime + 0.3
      );
      oscillator2.frequency.exponentialRampToValueAtTime(
        baseFreq * 3,
        this.audioContext.currentTime + 0.3
      );

      gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(
        0.01,
        this.audioContext.currentTime + 0.3
      );

      oscillator1.start(this.audioContext.currentTime);
      oscillator2.start(this.audioContext.currentTime);
      oscillator1.stop(this.audioContext.currentTime + 0.3);
      oscillator2.stop(this.audioContext.currentTime + 0.3);
    };
  }

  // 创建掉落音效
  createDropSound() {
    return (volume = 0.2) => {
      if (!this.enabled || !this.audioContext) return;

      const oscillator = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator.connect(gainNode);
      gainNode.connect(this.masterGain);

      oscillator.type = "sine";
      oscillator.frequency.setValueAtTime(400, this.audioContext.currentTime);
      oscillator.frequency.exponentialRampToValueAtTime(
        200,
        this.audioContext.currentTime + 0.2
      );

      gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(
        0.01,
        this.audioContext.currentTime + 0.2
      );

      oscillator.start(this.audioContext.currentTime);
      oscillator.stop(this.audioContext.currentTime + 0.2);
    };
  }

  // 创建游戏结束音效
  createGameOverSound() {
    return (volume = 0.6) => {
      if (!this.enabled || !this.audioContext) return;

      const oscillator = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator.connect(gainNode);
      gainNode.connect(this.masterGain);

      oscillator.type = "sawtooth";
      oscillator.frequency.setValueAtTime(300, this.audioContext.currentTime);
      oscillator.frequency.exponentialRampToValueAtTime(
        100,
        this.audioContext.currentTime + 1.0
      );

      gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(
        0.01,
        this.audioContext.currentTime + 1.0
      );

      oscillator.start(this.audioContext.currentTime);
      oscillator.stop(this.audioContext.currentTime + 1.0);
    };
  }

  // 创建点击音效
  createClickSound() {
    return (volume = 0.3) => {
      if (!this.enabled || !this.audioContext) return;

      const oscillator = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator.connect(gainNode);
      gainNode.connect(this.masterGain);

      oscillator.type = "square";
      oscillator.frequency.setValueAtTime(800, this.audioContext.currentTime);

      gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(
        0.01,
        this.audioContext.currentTime + 0.1
      );

      oscillator.start(this.audioContext.currentTime);
      oscillator.stop(this.audioContext.currentTime + 0.1);
    };
  }

  // 创建道具音效
  createPowerUpSound() {
    return (volume = 0.4) => {
      if (!this.enabled || !this.audioContext) return;

      const oscillator1 = this.audioContext.createOscillator();
      const oscillator2 = this.audioContext.createOscillator();
      const gainNode = this.audioContext.createGain();

      oscillator1.connect(gainNode);
      oscillator2.connect(gainNode);
      gainNode.connect(this.masterGain);

      oscillator1.type = "sine";
      oscillator2.type = "square";

      oscillator1.frequency.setValueAtTime(400, this.audioContext.currentTime);
      oscillator2.frequency.setValueAtTime(600, this.audioContext.currentTime);

      oscillator1.frequency.exponentialRampToValueAtTime(
        800,
        this.audioContext.currentTime + 0.2
      );
      oscillator2.frequency.exponentialRampToValueAtTime(
        1200,
        this.audioContext.currentTime + 0.2
      );

      gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(
        0.01,
        this.audioContext.currentTime + 0.2
      );

      oscillator1.start(this.audioContext.currentTime);
      oscillator2.start(this.audioContext.currentTime);
      oscillator1.stop(this.audioContext.currentTime + 0.2);
      oscillator2.stop(this.audioContext.currentTime + 0.2);
    };
  }

  // 创建成就音效
  createAchievementSound() {
    return (volume = 0.5) => {
      if (!this.enabled || !this.audioContext) return;

      // 播放一系列上升的音符
      const notes = [523.25, 659.25, 783.99, 1046.5]; // C5, E5, G5, C6

      notes.forEach((freq, index) => {
        setTimeout(() => {
          const oscillator = this.audioContext.createOscillator();
          const gainNode = this.audioContext.createGain();

          oscillator.connect(gainNode);
          gainNode.connect(this.masterGain);

          oscillator.type = "sine";
          oscillator.frequency.setValueAtTime(
            freq,
            this.audioContext.currentTime
          );

          gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
          gainNode.gain.exponentialRampToValueAtTime(
            0.01,
            this.audioContext.currentTime + 0.3
          );

          oscillator.start(this.audioContext.currentTime);
          oscillator.stop(this.audioContext.currentTime + 0.3);
        }, index * 100);
      });
    };
  }

  // 播放音效
  playSound(soundName, volume = 1.0) {
    if (!this.enabled || !this.initialized) return;

    // 恢复音频上下文（某些浏览器需要用户交互后才能播放音频）
    if (this.audioContext.state === "suspended") {
      this.audioContext.resume();
    }

    const sound = this.sounds.get(soundName);
    if (sound) {
      sound(volume * this.volume);
    }
  }

  // 设置主音量
  setVolume(volume) {
    this.volume = Utils.clamp(volume, 0, 1);
    if (this.masterGain) {
      this.masterGain.gain.value = this.volume;
    }
  }

  // 获取音量
  getVolume() {
    return this.volume;
  }

  // 启用/禁用音效
  setEnabled(enabled) {
    this.enabled = enabled;
    if (!enabled && this.audioContext) {
      this.audioContext.suspend();
    } else if (enabled && this.audioContext) {
      this.audioContext.resume();
    }
  }

  // 检查是否启用
  isEnabled() {
    return this.enabled;
  }

  // 播放背景音乐（简单的循环音调）
  playBackgroundMusic() {
    if (!this.enabled || !this.audioContext) return;

    // 创建简单的背景音乐循环
    const playNote = (frequency, duration, delay = 0) => {
      setTimeout(() => {
        if (!this.enabled) return;

        const oscillator = this.audioContext.createOscillator();
        const gainNode = this.audioContext.createGain();

        oscillator.connect(gainNode);
        gainNode.connect(this.masterGain);

        oscillator.type = "sine";
        oscillator.frequency.setValueAtTime(
          frequency,
          this.audioContext.currentTime
        );

        gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(
          0.01,
          this.audioContext.currentTime + duration
        );

        oscillator.start(this.audioContext.currentTime);
        oscillator.stop(this.audioContext.currentTime + duration);
      }, delay);
    };

    // 简单的旋律循环
    const melody = [
      { freq: 523.25, duration: 0.5 }, // C5
      { freq: 659.25, duration: 0.5 }, // E5
      { freq: 783.99, duration: 0.5 }, // G5
      { freq: 659.25, duration: 0.5 }, // E5
    ];

    let currentTime = 0;
    melody.forEach((note) => {
      playNote(note.freq, note.duration, currentTime * 1000);
      currentTime += note.duration + 0.1;
    });

    // 循环播放
    setTimeout(() => {
      if (this.enabled) {
        this.playBackgroundMusic();
      }
    }, (currentTime + 2) * 1000);
  }

  // 停止背景音乐
  stopBackgroundMusic() {
    this.enabled = false;
    setTimeout(() => {
      this.enabled = true;
    }, 100);
  }
}

// 创建全局音频管理器实例
window.AudioManager = new AudioManager();

// 导出
if (typeof module !== "undefined" && module.exports) {
  module.exports = AudioManager;
}
